package com.friends.utils.pdf;

import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.List;

@Slf4j
public class PdfUtil {
/*
    public static void pdf2Pic(String pdfPath, String path) throws IOException, PDFException, PDFSecurityException {
        org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        float rotation = 0f;

        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage)
              document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;
            try {
                String imgName = i + ".png";
                System.out.println(imgName);
                File file = new File(path + imgName);
                ImageIO.write(rendImage, "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
    }*/

    /**
     *
     * @param pdfPath  pdf路径
     * @param pageNo   生成的页码
     * @return
     * @throws IOException
     * @throws PDFException
     * @throws PDFSecurityException
     */
    public static ByteArrayOutputStream getPdfToPic(String pdfPath, int pageNo){
        ByteArrayOutputStream outputStream = null;
        BufferedImage image = null;
        org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
        try {
            outputStream = new ByteArrayOutputStream();
            document.setUrl(new URL(pdfPath));
            //缩放比例
            float scale = 2.5f;
            //旋转角度
            float rotation = 0f;

            image = (BufferedImage)
              document.getPageImage(pageNo, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            Graphics graphics = image.getGraphics();

            ClassPathResource fontResource = new ClassPathResource("font/SimSun.ttf");
            try (InputStream inputStream = fontResource.getInputStream() ){
                graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, inputStream));
            }catch (IOException e){
                log.error("set font error");
            }
            RenderedImage rendImage = image;
            ImageIO.write(rendImage, "png", outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            image.flush();
            document.dispose();
        }
        return outputStream;
    }


    public static ByteArrayOutputStream manipulatePdfAdd(String src, List<ContractSignContent> text) throws Exception {
        // 黑体
        String fontPath = "font/SimHei.ttf";
        ClassPathResource fontResource = new ClassPathResource(fontPath);
        BaseFont bf = BaseFont.createFont(fontResource.getPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        log.info("转换PDF路径{}, 字体 {}", fontResource.getPath(), bf);

//        宋体
//        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        PdfReader pdfReader = null;
        PdfStamper stamper = null;
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();

            pdfReader =  new PdfReader(new URL(src));
            stamper = new PdfStamper(pdfReader, outputStream);

            for (ContractSignContent contractSignContent : text) {
                if (StringUtils.isBlank(contractSignContent.getValue())) {
                    continue;
                }
                PdfContentByte canvas = stamper.getOverContent(contractSignContent.getPageNo() + 1);
                float width = pdfReader.getPageSize(contractSignContent.getPageNo() + 1).getWidth();
                float height = pdfReader.getPageSize(contractSignContent.getPageNo() + 1).getHeight();
                BigDecimal widthV = new BigDecimal(String.valueOf(width));
                BigDecimal heightV = new BigDecimal(String.valueOf(height));
                BigDecimal x = widthV.multiply(new BigDecimal(String.valueOf(contractSignContent.getCoordinateX())));
                BigDecimal y = heightV.multiply(new BigDecimal(String.valueOf(contractSignContent.getCoordinateY())));
                //初始阶段完成 开始替换
                canvas.saveState();
                //替换
                //加载文本
                canvas.beginText();
                //设置文本为中文、和字体大小
                canvas.setFontAndSize(bf, 12);
                //单位
                //设置坐标
                canvas.setTextMatrix(x.floatValue(), y.floatValue() + 6);
                //设置文本
                canvas.showText(contractSignContent.getValue());
                //结束加载文本
                canvas.endText();
            }

            return outputStream;
        } catch (Exception e) {
            log.error("转换合同有误" + e.getMessage(), e);
        } finally {
            if (stamper != null) {
                stamper.close();
            }
            if (pdfReader != null) {
                pdfReader.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
        return null;
    }

//    public static void main(String[] args) throws Exception {
//        ObjectMapper objectMapper = new ObjectMapper();
//        String a= "[{\"key\":\"1a243961-926d-4580-88fe-0ed689add7a3\",\"value\":\"你好啊\",\"label\":\"请输入文字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"TEXT\",\"coordinateX\":0.515562,\"coordinateY\":0.71375984,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":false},{\"key\":\"3b2d2b0d-ad13-432a-9f3a-89dc78970675\",\"value\":\"12\",\"label\":\"请输入数字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"NUMBER\",\"coordinateX\":0.7911976,\"coordinateY\":0.67931765,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":true},{\"key\":\"1a243961-926d-4580-88fe-0ed689add7a3\",\"value\":\"你好啊\",\"label\":\"请输入文字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"TEXT\",\"coordinateX\":0.515562,\"coordinateY\":0.71375984,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":false},{\"key\":\"3b2d2b0d-ad13-432a-9f3a-89dc78970675\",\"value\":\"12\",\"label\":\"请输入数字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"NUMBER\",\"coordinateX\":0.7911976,\"coordinateY\":0.67931765,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":true},{\"key\":\"1a243961-926d-4580-88fe-0ed689add7a3\",\"value\":\"你好啊\",\"label\":\"请输入文字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"TEXT\",\"coordinateX\":0.515562,\"coordinateY\":0.71375984,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":false},{\"key\":\"3b2d2b0d-ad13-432a-9f3a-89dc78970675\",\"value\":\"12\",\"label\":\"请输入数字\",\"operatorId\":11097,\"type\":\"BRANCH\",\"paramFormatType\":\"NUMBER\",\"coordinateX\":0.7911976,\"coordinateY\":0.67931765,\"pageNo\":0,\"autoWrite\":false,\"contractTimeType\":null,\"required\":true}]";
//        ByteArrayOutputStream byteArrayOutputStream = manipulatePdfAdd("https://cicero-archive-test.oss-cn-shanghai.aliyuncs.com/10000/DOCUMENT/20230210/oonc8hv92itqndin.pdf?OSSAccessKeyId=LTAI4Fvrb2kNa3Zhc2a9F5PV&Expires=1690268295&Signature=blDGQoGpGWRm3UQ0V5ZUG7J4%2FpE%3D", objectMapper.readValue(a, new TypeReference<>() {
//        }));
//        File file = new File("D:\\合同测试.pdf");
//        FileOutputStream fos = new FileOutputStream(file);
//        StreamUtils.copy(byteArrayOutputStream.toByteArray(), fos);
//        fos.close();
//    }

}
